package com.concurrent.aqslock.part8.reent;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 演示可中断式获取锁
 */
public class InterruptReenTrant {
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] arg0) {

        Thread t1 = new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + " before get lock");
                lock.lockInterruptibly();
                Thread.sleep(3000);
                System.out.println(Thread.currentThread().getName() + " after get lock");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if(lock.isHeldByCurrentThread()){
                    System.out.println(Thread.currentThread().getName()+" unlock");
                    lock.unlock();
                }
            }
        }, "first thread");

        Thread t2 = new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + " before get lock");
                lock.lockInterruptibly();
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + " after get lock");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if(lock.isHeldByCurrentThread()){
                    System.out.println(Thread.currentThread().getName()+" unlock");
                    lock.unlock();
                }
            }
        }, "second thread");

        t1.start();
        t2.start();
        // 尝试注释和不注释下面代码
        t1.interrupt();
    }

}
